﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace GenBenEditor
{
    public partial class PageEditor : UserControl
    {

        public Map map;
        public LayerSelector layers;
        public MiniMap minimap;
        
        public PageEditor()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
        }

        public void SetMembers(Map map, LayerSelector layers, MiniMap minimap)
        {
            this.map = map;
            this.layers = layers;
            this.minimap = minimap;

            layers.repaint_map += new LayerSelector.RepaintMapHandler(RepaintMap);
            minimap.repaint_map += new MiniMap.RepaintMapHandler(RepaintMap);
        }

        private void RepaintMap()
        {
            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (e.ClipRectangle == ClientRectangle)
            {
                e.Graphics.FillRectangle(Brushes.White, ClientRectangle);
                e.Graphics.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1);

                if (map != null && layers != null)
                    if (map.positioned_pages[minimap.selected_page_y, minimap.selected_page_x] != null)
                        for (uint i = 0; i < 6; ++i)
                            if (layers.DrawLayer((int)i)) PaintLayer(i, e.Graphics);
            }

            base.OnPaint(e);
        }

        protected void PaintLayer(uint layer, Graphics g)
        {
            if (layer < 2 || layer > 3 && layer < 6)
            {
                if (layer > 3)
                    layer -= 2;

                for (int y = 0; y < Page.height; ++y)
                {
                    for (int x = 0; x < Page.width; ++x)
                    {
                        TileId tile = map.positioned_pages[minimap.selected_page_y, minimap.selected_page_x].tiles[layer, y, x];
                        if (tile.tile == 240)
                            continue;
                        g.DrawImage(map.tilesets[tile.tileset].bitmap, 1 + x * Tileset.tile_width, 
                            1 + y * Tileset.tile_height, map.tilesets[tile.tileset].GetTileRect(tile.tile), 
                            GraphicsUnit.Pixel); 
                    }
                }
            }
        }
    }
}
